const hex = require("./hex");
const events = require("./events").createEvents();
const nfc = wx.getNFCAdapter();
console.log(nfc);
let hasStart = false;
let uids = [];
let curdata;

nfc.onDiscovered(function (data) {
  console.log(data);
  curdata = data;
  let uid = hex.bytesToHex(data.id);
  uids.push(uid);
  events.emit("read", uid, uids);
})
module.exports = events.extend(["read"], {
  get hasStart() {
    return hasStart;
  },
  start() {
    let that = this;
    if(hasStart){
      return;
    }
    hasStart = true;
    nfc.startDiscovery();
  },
  close(){
    var nfcv = nfc.getNfcV();
    nfcv.close();
  },
  connect() {
    console.log("开始连接标签");
    return new Promise((resolve, reject) => {
      var nfcv = nfc.getNfcV();
      nfcv.connect({
        fail(err) {
          console.log(err);
          reject(reject);
        },
        success(res) {
          console.log("连接标签");
          console.log(res);
          resolve(res);
        }
      });
    });
  },
  transceive(buffer) {
    return new Promise((resolve, reject) => {
      var nfcv = nfc.getNfcV();
      nfcv.transceive({
        data: new Uint8Array(buffer).buffer,
        success(data) {
          console.log("标签里面的数据");
          console.log([...new Uint8Array(data.data)]);
          resolve([...new Uint8Array(data.data)]);
        },
        fail(err) {
          reject(err);
          console.log(err);
        }
      })
    })
  },
  async setBlock(buffer){
    var size=parseInt((buffer.length+3)/4)-1;
    var slength=buffer.length;
    buffer.length=(size+1)*4;
    buffer.fill(0,slength,buffer.length)
    console.log("要写入的数据:"+size);
    console.log(buffer);
    for(var i=0;i<=size;i++){
      var res= await this.transceive([0x22, 0x21, ...new Uint8Array(curdata.id), i,...buffer.slice(i*4,i*4+4)]);
      if(res[0]!=0){
        return false;
      }
    }
    return true;
  },
  async getBlock(start, size) {
    return await this.transceive([0x22, 0x23, ...new Uint8Array(curdata.id), start, size]);
  },
  async getAfi() {
    var res= await this.transceive([0x22, 0x2B, ...new Uint8Array(curdata.id)]);
    return res[11];
  },
  async setAfi(byte) {
    return await this.transceive([0x22, 0x27, ...new Uint8Array(curdata.id),byte]);
  },
  stop() {
    hasStart = false;
    uids.length = 0;
    nfc.stopDiscovery();
    nfc.offDiscovered();
  },
})